package auser;

import java.io.IOException;
import java.util.Enumeration;
import java.util.Iterator;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet implementation class for Servlet: ApplicationServlet
 *
 */
 public class LoginServlet extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
    /* (non-Java-doc)
	 * @see javax.servlet.http.HttpServlet#HttpServlet()
	 */
	public LoginServlet() {
		super();
	}   	
	
	/* (non-Java-doc)
	 * @see javax.servlet.http.HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		elaborateRequest(request,response);
	}  	
	
	/* (non-Java-doc)
	 * @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		elaborateRequest(request,response);
	}   	
	
	protected void loginForm(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		
		for (Enumeration e = session.getAttributeNames(); e.hasMoreElements();) {
			String element = (String)e.nextElement();
			session.removeAttribute(element);
		}
		session.invalidate();
		request.getRequestDispatcher("/WEB-INF/jsp/pages/login.jsp").include(request, response);
		
	}
	
	protected void autentication(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Utente user = new Utente();
		user.setUserId("agordo_admin");
		user.setDescrizione("Amministratore");
		user.setRuoli("amministratore,contabile,soc");
		
		Circolo circolo = new Circolo();
		circolo.setCodice("agordo");
		circolo.setDescrizione("Circolo El Broi Agordo");
		circolo.setIndirizzo("via Rova Agordo (Bl)");
		
		
		HttpSession session = request.getSession();
		
		session.setAttribute("utenteCorrente",user);
		session.setAttribute("circoloCorrente",circolo);
		
		response.sendRedirect(request.getContextPath() +"/app");
	}
	protected void elaborateRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	    String command = request.getPathInfo();
	    if(command == null) command = request.getServletPath();
	    
	    if(command.equals("/loginForm")) loginForm(request,response);
	    if(command.equals("/autentication")) autentication(request,response);
	    else loginForm(request,response);
	     
	    
	}


}